package com.davy.gridpoint.activity;

import static android.view.View.VISIBLE;

import android.content.Intent;
import android.graphics.drawable.Drawable;
import android.os.Bundle;
import android.view.View;
import android.widget.TextView;

import com.davy.gridpoint.BaseActivity;
import com.davy.gridpoint.R;
import com.davy.gridpoint.utils.StringUtils;
import com.davy.gridpoint.utils.ToastUtil;

import org.osmdroid.api.IMapController;
import org.osmdroid.config.Configuration;
import org.osmdroid.events.MapEventsReceiver;
import org.osmdroid.tileprovider.tilesource.TileSourceFactory;
import org.osmdroid.tileprovider.tilesource.XYTileSource;
import org.osmdroid.util.GeoPoint;
import org.osmdroid.views.MapView;
import org.osmdroid.views.overlay.MapEventsOverlay;
import org.osmdroid.views.overlay.Marker;
import org.osmdroid.views.overlay.Overlay;

import java.io.File;
import java.text.DecimalFormat;
import java.util.ArrayList;
import java.util.List;

public class MapActivity extends BaseActivity {
    private MapView mapView;
    private TextView tvTitle, tvRight;
    private int type = 0;
    private String mLongitude, mLatitude, mAltitude;
    protected DecimalFormat decimalFormat;
    protected DecimalFormat decimalFormat1;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_map);
        type = getIntent().getIntExtra("isType", 0);
        statusbar4();
        decimalFormat = new DecimalFormat("#.00000000");
        decimalFormat1 = new DecimalFormat("#.00");
        // 设置 UserAgent
        Configuration.getInstance().setUserAgentValue("MyApp/1.0");
        // 初始化配置
//        Configuration.getInstance().load(this, PreferenceManager.getDefaultSharedPreferences(this));

        tvTitle = findViewById(R.id.tvTitle);
        tvTitle.setText("地图");
        tvRight = findViewById(R.id.tvRight);
        tvRight.setText("确认");
        tvRight.setVisibility(VISIBLE);
        tvRight.setOnClickListener(v -> {
            if (StringUtils.isEmpty(mLongitude)) return;
            if (StringUtils.isFastClick()) return;

            Intent intent = new Intent();
            intent.putExtra("mLongitude", mLongitude);
            intent.putExtra("mLatitude", mLatitude);
            intent.putExtra("mAltitude", mAltitude);
            setResult(RESULT_OK, intent);
            finish(); // 关闭当前Activity
        });
        mapView = findViewById(R.id.mapView);
        mapView.setUseDataConnection(true);
        // 设置初始地图位置
        mapController = mapView.getController();
        mapController.setZoom(20.0);
//        mapView.setUseDataConnection(false);  // 强制使用离线瓦片
//        mapView.setTileSource(TileSourceFactory.MAPNIK_VECTOR);
//        mapView.setTileSource(TileSourceFactory.MAPNIK); // 使用OSM默认街道图

        // 根据屏幕密度计算缩放后尺寸（如 512px）
        float scale = getResources().getDisplayMetrics().density;
        int tileSize = (int) (256 * scale); // 高密度屏推荐 512

        // 使用在线地图源（确保网络正常）
        mapView.setTileSource(new XYTileSource("OpenStreetMap", 4, 22, tileSize, ".png", new String[]{"https://a.tile.openstreetmap.org/", "https://b.tile.openstreetmap.org/", "https://c.tile.openstreetmap.org/"}));

        // 启用交互控件
        mapView.setBuiltInZoomControls(true);
        mapView.setMultiTouchControls(true); // 启用多指缩放

        double aLatitude;
        double aLongitude;
//        if (type == 1) {
//            aLatitude = Double.valueOf(getIntent().getStringExtra("latitude") + "");
//            aLongitude = Double.valueOf(getIntent().getStringExtra("longitude") + "");
//        } else {
//            aLatitude = Double.valueOf(MainActivity.mLatitude);
//            aLongitude = Double.valueOf(MainActivity.mLongitude);
//        }
        GeoPoint startPoint = new GeoPoint(39.9042, 116.4074); // 北京坐标
        mapController.setCenter(startPoint);
        // 设置初始位置
//        GeoPoint startPoint = new GeoPoint(aLatitude, aLongitude);
//        mapView.getController().setCenter(startPoint);
        refreshMarkers(startPoint);

        // 添加点击监听器
        mapView.getOverlays().add(new MapEventsOverlay(new MapEventsReceiver() {
            @Override
            public boolean singleTapConfirmedHelper(GeoPoint point) {
                handleMapClick(point); // 处理点击事件
                return true;
            }

            @Override
            public boolean longPressHelper(GeoPoint point) {
                return false;
            }
        }));
    }

    @Override
    public void onResume() {
        super.onResume();
        mapView.onResume(); // 必须调用！
    }

    @Override
    public void onPause() {
        super.onPause();
        mapView.onPause(); // 必须调用！
    }

    private void handleMapClick(GeoPoint point) {
        double latitude = point.getLatitude();
        double longitude = point.getLongitude();
        mLongitude = decimalFormat.format(longitude);
        mLatitude = decimalFormat.format(latitude);
        mAltitude = decimalFormat1.format(point.getAltitude());
        // 显示经纬度信息
        ToastUtil.showNew(mContext, "Lat: " + latitude + ", Lon: " + longitude);
        refreshMarkers(point);
    }

    private IMapController mapController;
    private final List<Marker> activeMarkers = new ArrayList<>();

    // 清除所有标记点并添加新标记点
    public void refreshMarkers(GeoPoint newLocations) {
        clearAllMarkers();

        addMarker(newLocations);

        // 如果有新标记，将地图中心移动到第一个标记位置
        mapController.animateTo(newLocations);
    }

    // 添加单个标记点
    private void addMarker(GeoPoint point) {
        Marker marker = new Marker(mapView);
        marker.setPosition(point);

        // 设置自定义图标（可选）
        try {
            Drawable icon = getResources().getDrawable(R.mipmap.icon_dw);
            marker.setIcon(icon);
        } catch (Exception e) {
            // 使用默认图标
            marker.setAnchor(Marker.ANCHOR_CENTER, Marker.ANCHOR_BOTTOM);
        }

        // 添加到地图和管理列表
        mapView.getOverlays().add(marker);
        activeMarkers.add(marker);

        // 刷新地图
        mapView.invalidate();
    }

    // 清除所有标记点
    private void clearAllMarkers() {
        // 从地图上移除
        List<Overlay> overlays = mapView.getOverlays();
        overlays.removeAll(activeMarkers);

        // 清空管理列表
        activeMarkers.clear();

        // 刷新地图
        mapView.invalidate();
    }

    public void imgBack(View view) {
        finish();
    }
}
